Inheritance in C#

One of the most important aspects of Object Oriented Programming (OOP), which has been made to C #, is legacy, the ability to create classes that parents handle some aspects of classes. The net framework is built on the whole concept, resulting in "everything is a thing" even a simple number is an example of a class, which is the system. The object exits from the class, though. Net helps you a little bit, so you can assign a number directly instead of creating a new example of the example. Integer class

Understanding this topic can be a bit difficult, but sometimes it helps with some examples, then start with one of them:


public class Animal
{
    public void Greet()
    {
        Console.WriteLine("Hello, I'm some sort of animal!");
    }
}

public class Dog : Animal
{

}

First of all, we define an animal class, in which there is a simple way of greeting. Then we define a dog class, and with a colon, we tell C # that the dog class should be from the animal class. The beautiful thing about this is that it also makes sense in the real world - is a dog, of course, try to walk an animal using classes:


Animal animal = new Animal();
animal.Greet();
Dog dog = new Dog();
dog.Greet();

If you run this example, you will see that even though we have not defined the method of method for the dog class, it still knows how to greet us, because this animal class gets this method Does. However, this greeting is an unknown, so we customize it when we know which animal it is:


public class Animal
{
    public virtual void Greet()
    {
        Console.WriteLine("Hello, I'm some sort of animal!");
    }
}

public class Dog : Animal
{
    public override void Greet()
    {
        Console.WriteLine("Hello, I'm a dog!");
    }
}

In addition to the method of adding to the dog category, you should keep in mind two things: I have added the virtual keyword to the method in the animal category, and on the dog class, I use the overridden keyword.

In C # you are not allowed to override a class member, unless it is marked as a virtual. If you want, you can still use the legacy method, even when you override it, you can use the base keyword.


public override void Greet()
{
    base.Greet();
    Console.WriteLine("Yes I am - a dog!");
}

There is only one thing inherited in ways, though. In fact, all members of the class will be heirs, which will include fields and properties. Just remember the rules of visibilty as discussed in the last chapter

Legacy is not from one class to another - you can have a whole hierarchy of classes, which comes from each other. For example, we can make a puppy class, which comes from our dog class, which in turn reaches the animal class. Whatever you can not do in C #, it is a class to meet many other classes at the same time. As stated, multiple heritage is not supported by C #.